import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getArticles, getArticleById, getCategories, getTags } from '@/utils/api'

export const useBlogStore = defineStore('blog', () => {
  // 状态定义
  const state = {
    articles: ref([]),
    categories: ref([]),
    tags: ref([]),
    currentArticle: ref(null),
    isLoading: ref(false),
    error: ref(null)
  }

  /**
   * 验证文章数据完整性
   */
  const validateArticle = (article) => {
    if (!article || typeof article !== 'object') {
      console.warn('Invalid article data:', article)
      return null
    }

    return {
      id: Number(article.id) || 0,
      title: String(article.title || '未命名文章'),
      body: String(article.body || '暂无内容'),
      userId: Number(article.userId || 1),
      coverImage: String(article.coverImage || '/default-cover.jpg'),
      createdAt: article.createdAt || new Date().toISOString(),
      // 其他扩展字段
      ...(article.additionalData || {})
    }
  }

  /**
   * 获取文章列表（完整错误处理）
   */
  const fetchArticles = async (options = {}) => {
    const { forceRefresh = false } = options

    try {
      // 如果已有数据且不强制刷新，则直接返回
      if (state.articles.value.length > 0 && !forceRefresh) {
        return state.articles.value
      }

      state.isLoading.value = true
      state.error.value = null

      const response = await getArticles()
      const rawData = Array.isArray(response?.data) ? response.data : response

      // 数据清洗和验证
      state.articles.value = []
      if (Array.isArray(rawData)) {
        for (const item of rawData) {
          const validArticle = validateArticle(item)
          if (validArticle) {
            state.articles.value.push(validArticle)
          }
        }
      }

      // 空数据回退
      if (state.articles.value.length === 0) {
        console.warn('Received empty article list, using fallback data')
        state.articles.value = [getFallbackArticle()]
      }

      return state.articles.value
    } catch (err) {
      state.error.value = err.message || 'Failed to fetch articles'
      console.error('Article fetch error:', err)

      // 错误回退
      state.articles.value = [getFallbackArticle()]
      throw err // 重新抛出错误供组件处理
    } finally {
      state.isLoading.value = false
    }
  }

  /**
   * 获取单篇文章（带缓存）
   */
  const fetchArticle = async (id) => {
    if (!id) {
      const err = new Error('Missing article ID')
      state.error.value = err.message
      throw err
    }

    try {
      // 检查缓存
      if (state.currentArticle.value?.id === id) {
        return state.currentArticle.value
      }

      state.isLoading.value = true
      state.error.value = null

      const response = await getArticleById(id)
      const validArticle = validateArticle(response?.data || response)

      if (!validArticle) {
        throw new Error('Invalid article data structure')
      }

      state.currentArticle.value = validArticle
      return validArticle
    } catch (err) {
      state.error.value = err.message || 'Failed to fetch article'
      console.error('Fetch article error:', err)

      // 返回回退数据
      const fallback = getFallbackArticle(id)
      state.currentArticle.value = fallback
      return fallback
    } finally {
      state.isLoading.value = false
    }
  }

  /**
   * 获取分类列表
   */
  const fetchCategories = async () => {
    try {
      state.isLoading.value = true
      state.error.value = null

      const response = await getCategories()
      const rawData = Array.isArray(response?.data) ? response.data : response

      // 数据清洗
      state.categories.value = []
      if (Array.isArray(rawData)) {
        state.categories.value = rawData
          .filter(cat => cat && cat.id && cat.name)
          .map(cat => ({
            id: Number(cat.id),
            name: String(cat.name),
            count: Number(cat.count || 0)
          }))
      }

      // 默认分类
      if (state.categories.value.length === 0) {
        state.categories.value = [
          { id: 1, name: '技术', count: 0 },
          { id: 2, name: '生活', count: 0 }
        ]
      }

      return state.categories.value
    } catch (err) {
      state.error.value = err.message || 'Failed to fetch categories'
      console.error('Fetch categories error:', err)
      state.categories.value = []
      throw err
    } finally {
      state.isLoading.value = false
    }
  }

  /**
   * 获取标签列表
   */
  const fetchTags = async () => {
    try {
      state.isLoading.value = true
      state.error.value = null

      const response = await getTags()
      const rawData = Array.isArray(response?.data) ? response.data : response

      // 数据清洗
      state.tags.value = []
      if (Array.isArray(rawData)) {
        state.tags.value = [...new Set(rawData)]
          .filter(tag => tag && typeof tag === 'string')
          .sort()
      }

      // 默认标签
      if (state.tags.value.length === 0) {
        state.tags.value = ['Vue', 'JavaScript', 'CSS']
      }

      return state.tags.value
    } catch (err) {
      state.error.value = err.message || 'Failed to fetch tags'
      console.error('Fetch tags error:', err)
      state.tags.value = []
      throw err
    } finally {
      state.isLoading.value = false
    }
  }

  /**
   * 生成回退文章数据
   */
  const getFallbackArticle = (id = 0) => ({
    id: id,
    title: '示例文章',
    body: '这是系统自动生成的示例内容，因为无法获取真实数据。',
    userId: 1,
    coverImage: '/default-cover.jpg',
    createdAt: new Date().toISOString()
  })

  /**
   * 重置store状态
   */
  const resetStore = () => {
    state.articles.value = []
    state.categories.value = []
    state.tags.value = []
    state.currentArticle.value = null
    state.error.value = null
  }

  return {
    // 状态
    articles: state.articles,
    categories: state.categories,
    tags: state.tags,
    currentArticle: state.currentArticle,
    isLoading: state.isLoading,
    error: state.error,

    // 方法
    fetchArticles,
    fetchArticle,
    fetchCategories,
    fetchTags,
    resetStore
  }
})